package com.google.code.timeeditapplication.view.implementation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.code.timeeditapplication.R;
import com.google.code.timeeditapplication.controller.implementation.ScheduleController;
import com.google.code.timeeditapplication.model.implementation.ICal2Schedule;
import com.google.code.timeeditapplication.model.implementation.Schedule;
import com.google.code.timeeditapplication.model.implementation.SearchResult;
import com.google.code.timeeditapplication.model.implementation.TimeEditCommunicator;

public class SearchResultViewActivity extends Activity implements Runnable {

	private ProgressDialog dialog;
	private ListView lv;
	private final ArrayList<SearchResult> searchResults = new ArrayList<SearchResult>();
	private final TimeEditCommunicator tEC = TimeEditCommunicator.getInstance();
	private final ArrayList<Schedule> selectedSchedules = new ArrayList<Schedule>();
	private int chosen;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.searchresultsview);
		this.lv = (ListView) findViewById(R.id.searchresultlist);

		this.lv.setAdapter(new ArrayAdapter<SearchResult>(this,
				android.R.layout.simple_list_item_1, this.tEC.getResults()));

		this.lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(final AdapterView<?> arg0, final View arg1,
					final int arg2, final long arg3) {
				/*
				 * for (int i = 0; i < lv.getCheckedItemPositions().size(); i++)
				 * { searchResults.add((SearchResult) lv.getAdapter().getItem(
				 * lv.getCheckedItemPositions().keyAt(i))); }
				 */
				showSchedule(arg2);
			}

		});
	}

	public void showSchedule(final int index) {
		this.chosen = index;
		this.dialog = ProgressDialog.show(this, "", "Downloading...", true);

		final Thread thread = new Thread(this);
		thread.start();
	}

	public void showSelectedSchedules(final View v) {
		this.dialog = ProgressDialog.show(this, "", "Downloading...", true);

		final Thread thread = new Thread(this);
		thread.start();
	}

	@SuppressWarnings("unused")
	private void _insertSelectedSchedules() throws FileNotFoundException {

		final ICal2Schedule converter = ICal2Schedule.getInstance();

		for (final SearchResult sR : this.searchResults) {
			try {
				final File schedule = new File(
						Environment.getExternalStorageDirectory() + "/tea/"
								+ sR.getName() + ".ics");
				if (!schedule.exists()) {
					this.tEC.downloadSchedule(sR.getId(),
							Environment.getExternalStorageDirectory() + "/tea/"
									+ sR.getName() + ".ics");
				}
			} catch (final IOException e) {
				// Auto-generated catch block
				e.printStackTrace();
			}
		}

		for (final SearchResult sR : this.searchResults) {
			this.selectedSchedules.add(converter.fileToSchedule(
					Environment.getExternalStorageDirectory() + "/tea/"
							+ sR.getName() + ".ics", sR.getName()));
		}
	}

	public void run() {
		/*
		 * if (selectedSchedules.size() != 0) { selectedSchedules.clear(); }
		 * 
		 * searchResults.clear();
		 * 
		 * SparseBooleanArray hej = lv.getCheckedItemPositions();
		 * 
		 * for (int i = 0; i < lv.getCheckedItemPositions().size(); i++) {
		 * searchResults.add((SearchResult) lv.getAdapter().getItem(
		 * lv.getCheckedItemPositions().keyAt(i))); } if (searchResults.size()
		 * != 0) {
		 * 
		 * Intent showSelectedSchedulesIntent = new Intent(this,
		 * DayViewActivity.class);
		 * 
		 * File dir = new File(Environment.getExternalStorageDirectory() +
		 * "/tea/"); if (!(dir.exists() && dir.isDirectory())) { dir.mkdirs(); }
		 * 
		 * try { _insertSelectedSchedules(); } catch (FileNotFoundException e) {
		 * // Auto-generated catch block e.printStackTrace(); }
		 * 
		 * ScheduleController.getInstance().setDay(selectedSchedules.get(0));
		 * 
		 * dialog.dismiss(); this.startActivity(showSelectedSchedulesIntent); }
		 */
		final Intent showSelectedSchedulesIntent = new Intent(this,
				DayViewActivity.class);
		final File dir = new File(Environment.getExternalStorageDirectory()
				+ "/tea/");
		if (!(dir.exists() && dir.isDirectory())) {
			dir.mkdirs();
		}

		try {
			final File schedule = new File(
					Environment.getExternalStorageDirectory() + "/tea/"
							+ this.tEC.getResults().get(this.chosen).getName()
							+ ".ics");
			if (!schedule.exists()) {
				this.tEC.downloadSchedule(this.tEC.getResults()
						.get(this.chosen).getId(),
						Environment.getExternalStorageDirectory()
								+ "/tea/"
								+ this.tEC.getResults().get(this.chosen)
										.getName() + ".ics");
			}
		} catch (final IOException e) {
			// Auto-generated catch block
			e.printStackTrace();
		}

		try {
			ScheduleController.getInstance().setActiveSchedule(
					ICal2Schedule.getInstance().fileToSchedule(
							Environment.getExternalStorageDirectory()
									+ "/tea/"
									+ this.tEC.getResults().get(this.chosen)
											.getName() + ".ics",
							this.tEC.getResults().get(this.chosen).getName()));
		} catch (final FileNotFoundException e) {
			// Auto-generated catch block
			e.printStackTrace();
		}

		this.dialog.dismiss();
		startActivity(showSelectedSchedulesIntent);
	}
}
